﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Security;
using WeddingEventManagement_API;

namespace WeddingEventManagementApp
{
    /// <summary>
    /// Contains static utility methods that can be used in any controller
    /// </summary>
    public static class Utility
    {
        /// <summary>
        /// Returns a MD5 hash from input string
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string MD5Hash(string input)
        {
            StringBuilder hash = new StringBuilder();
            MD5CryptoServiceProvider md5provider = new MD5CryptoServiceProvider();
            byte[] bytes = md5provider.ComputeHash(new UTF8Encoding().GetBytes(input));

            for (int i = 0; i < bytes.Length; i++)
            {
                hash.Append(bytes[i].ToString("x2"));
            }
            return hash.ToString();
            
        }

        /// <summary>
        /// Returns UserID from string
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        public static Guid GetUserID(string username)
        {
            return (Guid)Membership.GetUser(username).ProviderUserKey;
        }


        /// <summary>
        /// Returns Unix Timespan from DateTime
        /// </summary>
        /// <param name="date"></param>
        /// <returns></returns>
        public static long ToUnixTimespan(DateTime date)
        {
            TimeSpan tspan = date.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0));

            return (long)Math.Truncate(tspan.TotalSeconds);
        }

        /// <summary>
        /// Returns a relative time for an event start datetime
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string ToRelativeTime(DateTime dt)
        {

            if (DateTime.UtcNow > dt)
            {
                return "Occured on " + dt.ToLongDateString();
            }

            double days = dt.Subtract(TimeZone.CurrentTimeZone.ToLocalTime(DateTime.UtcNow)).TotalDays;

            
            if (TimeZone.CurrentTimeZone.ToLocalTime(DateTime.UtcNow).ToLongDateString() == dt.ToLongDateString())
            {
                return "Today";
            }
            if (days <= 1)
            {
                return "Tomorrow";
            }
            else
            {
                return Math.Ceiling(days) + " days from now";
            }
        }

        public static decimal CalculateInvoiceTotal(Invoice i)
        {
            InvoiceManager im = new InvoiceManager();
            return im.GetInvoiceTotal(i.InvoiceID);
        }
    }
}